﻿using System;
using System.Linq;
using System.Web.Security;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Medianamik.Core.Profile;
using Medianamik.Core.Security;
using Medianamik.Core.Sugar;
using Medianamik.Globalization;
using Roles = Medianamik.Core.Security.Roles;
using Medianamik.UI.Blog.Logic;


namespace Medianamik.UI.Blog.userControls
{
    public partial class EditUser : UserBaseUserControl
    {
        
        public override void Save()
        {
            if (Page.IsValid)
                SaveData();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            patAvatar.ControlInfo = new MedianamikControlInfo { Height = 50, Width = Unit.Pixel(50) };
            patAvatar.DisplayLabel = false;

            IsInEditionMode = !(CurrentUser == null || Guid.Equals(MedianamikUsers.SA, CurrentUser.ProviderUserKey));

            if (!Page.IsPostBack)
            {
                calExpirationDate.DatePopupButton.ToolTip = Translator.Translate("Medianamik_Controls", "OpenCalendarPopup");
			
	            if (IsInEditionMode)
                    BindData();             
            }
        }

        
        protected void cvPasswordStrength_ServerValidate(object sender, ServerValidateEventArgs e)
        {
            var password = e.Value;
            PasswordValidator validator = new PasswordValidator(Membership.Provider);
            var result = validator.ValidatePassword(password);

            if (result == PasswordValidationResult.Success)
            {
                e.IsValid = true;
            }
            else
            {
                e.IsValid = false;
            }
        }

        protected void cvPasswordCompare_ServerValidate(object sender, ServerValidateEventArgs e)
        {
            var password = e.Value;
            var comparePassword = txtConfirmPassword.Text;

            e.IsValid = password.CompareTo(comparePassword) == 0;
        }


        #region Propriétés
        protected MembershipUser CurrentUser
        {
            get
            {
				var user = ViewState["CurrentUser"] as MembershipUser;
				if (user == null)
				{
					user = Membership.GetUser(ItemId);
					ViewState["CurrentUser"] = user;
				}
				return user;
            }
        }

		protected Guid ItemId
		{
			get
			{
				Guid g;
				if (StringHelper.IsGuid(Request["id"], out  g))
				{
					return g;
				}
				return Guid.Empty;
			}
		}
        #endregion 

        /// <summary>
        /// Obtenir les donnés de base du formulaire
        /// </summary>
        private void BindData()
        {

            ddlLanguage.DataSource = ConfigManager.GetMedianamikCultures().Select(c=>c.CultureInfo );
            ddlLanguage.DataValueField = "Name";
            ddlLanguage.DataTextField = "DisplayName";
            ddlLanguage.DataBind();

            ddlGroups.DataSource = BlogGroups.GetGroups();
            ddlGroups.DataBind();

            ddlGroups.Items.Insert(0, new ListItem());

            var selectedRoles = Roles.GetGroupsForUser(CurrentUser.UserName);
            
            if (selectedRoles.Length > 0)
            {
                if (selectedRoles.Length == 1)
                {
                   var item = ddlGroups.Items.FindByText(Roles.GetGroupsForUser(CurrentUser.UserName)[0]);
                   if (item != null)
                       item.Selected = true;
                }
                else
                {
                    ddlGroups.Enabled = false;
                }
            }

            var profile = (UserProfile)UserProfile.Create(CurrentUser.UserName);

            var langItem = ddlLanguage.Items.Cast<ListItem>().FirstOrDefault(i => i.Value.Equals(profile.UICultureName, StringComparison.OrdinalIgnoreCase));
            if (langItem != null) { langItem.Selected = true; }

            txtCompleteName.Text = profile.FullName;
            txtEmail.Text = CurrentUser.Email;

            patAvatar.DataSource = profile.Avatar;
            chkActive.Checked = profile.Active.GetValueOrDefault();
            txtWebSiteURL.Text = profile.WebSiteUrl;
            txtNickname.Text = profile.Nickname;
            litSubscriptionDate.Text = profile.SubscriptionDate.HasValue ? profile.SubscriptionDate.GetValueOrDefault().ToString("yyyy/MM/dd hh:mm:ss") : "";
            txtNote.Text = profile.Note;

            calExpirationDate.SelectedDate = profile.ExpirationDate;
            chkApproved.Checked  = CurrentUser.IsApproved;            

        }

        /// <summary>
        /// Créer l'usager 
        /// </summary>
        private void SaveData()
        {
            //Sauvegarder les données du User
            CurrentUser.Email = txtEmail.Text;
            CurrentUser.IsApproved = chkApproved.Checked;           
            Membership.UpdateUser(CurrentUser);

            //Changer le mot de passe si nécessaire
            if (txtPassword.Text.Trim().Length > 0)
            {
                ChangeUserPassword(CurrentUser, txtPassword.Text.Trim());
            }

            //Sauvegarder les données du profile
            var profile = (UserProfile)UserProfile.Create(CurrentUser.UserName);
            profile.UICultureName = ddlLanguage.SelectedValue;
            profile.FullName = txtCompleteName.Text ;
            profile.ExpirationDate = calExpirationDate.SelectedDate;
            profile.Avatar = (patAvatar.GetValue() ?? "").ToString();
            profile.Active = chkActive.Checked;
            profile.WebSiteUrl = txtWebSiteURL.Text;
            profile.Nickname = txtNickname.Text;
            profile.Note = txtNote.Text;

            profile.Save();

            Core.Logging.LogEntryManager.LogUser(CurrentUser, "User Modified");

            if (CurrentUser.UserName == MedianamikContext.Current.MedianamikUser.UserName)
            {
                Session["UserCulture"] = profile.UICultureName;
            }

            if (ddlGroups.Enabled)
            {
                var selectedGroups = ddlGroups.SelectedValue;

                var notSelectedGroups = BlogGroups.GetGroups().Where(g => !g.EqualsIgnoreCase(selectedGroups));

                Roles.RemoveUserFromGroups(CurrentUser.UserName , notSelectedGroups.ToArray());
                Roles.AddUserToGroups(CurrentUser.UserName, new[] {selectedGroups});
            }
        }

        private void ChangeUserPassword(MembershipUser CurrentUser, string pNewPassword)
        {
            var tempPassword = CurrentUser.ResetPassword();
            CurrentUser.ChangePassword(tempPassword, pNewPassword);
        }

        protected void cblGroups_Required(object sender, ServerValidateEventArgs args)
        {
            args.IsValid = !(ddlGroups.SelectedValue == "") || !ddlGroups.Enabled;
        }
    }
}